package com.ambow.shop.controller;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.ambow.shop.action.Action;
import com.ambow.shop.action.impl.AddProductAction;
import com.ambow.shop.action.impl.DefaultAction;
import com.ambow.shop.action.impl.DeleteProductAction;
import com.ambow.shop.action.impl.EditProductAction;
import com.ambow.shop.action.impl.GetProductAction;
import com.ambow.shop.action.impl.InputProductAction;
import com.ambow.shop.action.impl.ListProductAction;
import com.ambow.shop.action.impl.UpdateProductAction;

/**
 * 产品控制器。
 * 
 * @author chunw
 *
 */
@WebServlet(name = "ProductController", urlPatterns = { "/product/*" })
@MultipartConfig
public class ProductController extends HttpServlet {

	private static final long serialVersionUID = 1L;

	public ProductController() {
		super();
	}

	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		process(request, response);
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		process(request, response);
	}

	private String getActionName(String uri) {
		return uri.substring(uri.lastIndexOf("/") + 1);
	}

	private void process(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		Action action = null;
		String actionName = getActionName(request.getRequestURI());
		// 还可以再改写，可以把这个内容写在配置文件中，然后通过发射直接生成对象；
		if (actionName.equals("get")) {
			action = new GetProductAction();
		} else if (actionName.equals("list")) {
			action = new ListProductAction();
		} else if (actionName.equals("input")) {
			action = new InputProductAction();
		} else if (actionName.equals("add")) {
			action = new AddProductAction();
		} else if (actionName.equals("delete")) {
			action = new DeleteProductAction();
		} else if (actionName.equals("edit")) {
			action = new EditProductAction();
		} else if (actionName.equals("update")) {
			action = new UpdateProductAction();
		} else {
			action = new DefaultAction();
		}

		String result = action.execute(request, response);
		if (result.equals("/home")) {
			response.sendRedirect(result);
		} else {
			request.getRequestDispatcher(result).forward(request, response);
		}
	}

}
